const Content = require('../model/content.model')
class ContentService {
    //添加用户
    async addContent(name, description, imgUrl, category,title,content) {
        const res = await Content.create({ name, description, imgUrl, category,title,content })
        return res.dataValues
    }
    // // 获取某个用户信息
    // async getOneUserInfo({ id,userName,phone,role}) {
    //     const whereOpt = {}
    //     id && Object.assign(whereOpt, { id })
    //     userName && Object.assign(whereOpt, { userName })
    //     phone&& Object.assign(whereOpt, { phone})
    //     role && Object.assign(whereOpt, { role })

    //     const res = await User.findOne({
    //         attributes: ['id', 'userName', 'password', 'role'],
    //         where: whereOpt
    //     })

    //     return res ? res.dataValues : null
    // }
    //依据类型获取内容
    async getContentByType(category,subcategory,pageNum, pageSize) {
        const whereOpt = {}
        category && Object.assign(whereOpt, { category })
        subcategory && Object.assign(whereOpt, { subcategory})
        
        const offset = (pageNum - 1) * pageSize
        const { count, rows }  = await Content.findAndCountAll({
            attributes: ['id', 'name','description','imgUrl','title','content','category','subcategory','contentUrl'],
            offset: offset,
            limit: pageSize * 1,
            where: whereOpt
        }
        )
        return {
            
            pageNum,
            pageSize,
            total: count,
            rows
        }
    }
    // 获取某个内容信息
    async getOneConInfo({ id,name }) {
        const whereOpt = {}
        id && Object.assign(whereOpt, { id })
        name && Object.assign(whereOpt, { name})
           const res = await Content.findOne({
            attributes: ['id', 'name','description','title','category'],
            where: whereOpt
        })

        return res ? res.dataValues : null
    }
    //
    // 修改内容
    async updateContent(id,contents) {
        const res = await Content.update(contents, { where: { id } })
        return res[0] > 0 ? true : false
        
    }
    // 删除内容
    async removeContent(id) {
        const res = await Content.destroy({
            where: { id }
        })
        return res > 0 ? true : false
    }
    
}

module.exports = new ContentService()